<?php
namespace com\rainiswalking\sonar_report\notice_plugins;

use com\rainiswalking\sonar_report\lib\CommonUtil;
use com\rainiswalking\sonar_report\lib\HttpUtil;

class DingdingNoticePlugin implements INoticePlugin {
    function notice($data, $cfg) {
        $notice_cfg = $cfg['notice']['dingding'];
        CommonUtil::assert_field_required($notice_cfg, 'url');

        $url = $notice_cfg['url'];
        $atMobiles = $this->_get_field_value($notice_cfg, 'atMobiles', '');
        $isAtAll = $this->_get_field_value($notice_cfg, 'isAtAll', false);
        $btns = array();
        if (isset($notice_cfg['btn_title']) && !empty($notice_cfg['btn_title'])) {
            $btns[] = array(
                'title'=>$notice_cfg['btn_title'],
                'actionURL'=>$notice_cfg['btn_actionURL'],
            );
        }

        $title = $data['title'];
        $body = $data['content'];
        $data = array(
            'actionCard'=>array(
                "title"=> $title,
                "text"=> "
### {$title} 
$body",
                "hideAvatar"=> "1",
                "btnOrientation"=> "0",
                "btns"=>$btns
            ),
            "msgtype"=>"actionCard",
            "at"=>array(
                'atMobiles'=>$atMobiles,
                'isAtAll'=>$isAtAll
            )

        );
        $_headers = array('header'=>array('Content-Type: application/json;charset=utf-8'));

        $ret = HttpUtil::post($url, json_encode($data), $_headers);
        $data = json_decode($ret, true);

        return $data['errcode'] == 0;
    }

    function _get_field_value($arr, $field, $default) {
        if (isset($arr[$field]) && $arr[$field] !== '') {
            return $arr[$field];
        }

        return $default;
    }
}